var tmplate={
				"deliverLocationOption":'<option value="@{locationValue}" ccy="@{ccyValue}">@{locationName}</option>'
			};

function dashboard() {
    this.callSuper();
    this.configuration = {
        "i18n": "nls/dashboard",
        "apis": "../../config/apis/dashboard"
    };
    this._viewIndex = "dashboard";

    // for location switcher
    /*
    this._location1 = "HK";
    this._location2 = "CN";
    
    this._ccyMapping = {
        "CN": "CNY",
        "HK": "HKD"
    };
    */

    // browser mode
    this.isBrowser = false;
    // customer data
    this.account = "";
    this.location = "";
    this.secureToken = "";
    // new dashboard object
    this.newGameDashboard = {};
}
//Dave
function getUrlValueByName(paramName){
    var paramValue="";
    var urlthis=location.href;
    urlthis=urlthis.substring(urlthis.indexOf('?')+1,urlthis.length);
    var arr=urlthis.split('&');
    if(arr!=null){
        for(var i=0;i<arr.length;i++){
            var parmNameValue=arr[i].split('=');
            if(parmNameValue!=null&&parmNameValue.length==2){
                if(parmNameValue[0]==paramName){
                    paramValue=parmNameValue[1];
                    break;
                }
            }
        }
    }
    return paramValue;
}
dashboard.prototype.dashboardHasParsed = function() {
    var self = this;

    // event binding
    iData.get("btnHome").click(function() {
        self.goBack("file:///web/postlogon/menu/menu.html?state="+getUrlValueByName('state'), true);
    });
    iData.get("btnDelivered").click(function() {
        if(getUrlValueByName("state")=='1'){
            self.goTo("file:///web/postlogon/dashboard/dashboard.html?state="+getUrlValueByName("state"), true);
        }else{
            self.goTo("file:///web/postlogon/dashboard/dashboard.html", true);
        }
    });
    iData.get("btnReceived").click(function() {
        //Dave
        //self.goTo("file:///web/postlogon/deliver/deliver.html", true);
        if(getUrlValueByName('state')=="1"){
            self.goTo("file:///web/postlogon/myLaisee/myLaiSee.html?state="+getUrlValueByName('state'), true);
        }else{
            self.goTo("file:///web/postlogon/myLaisee/myLaiSee.html", true);
        }
    });

    // init location switcher
    self.initLocSwither();

    // init the iScroll plugin at the end
    dashboardIScrollPluginInit.begin();

    // Get location list
    self.updateSettingLocation(self.configuration.settings.GreenPacketLocation);
    
    // get customerData from local db
    self.getCustomerInfo(self.getCustomerInfoCallback);
};

dashboard.prototype.updateSettingLocation = function(locationArray){
	var self = this;
	var LocationOptionHtml = '';
	for(var i=0;i < locationArray.length; i++){
		var options = {
				locationValue: locationArray[i].value,
				locationName : locationArray[i].name,
				ccyValue:locationArray[i].ccy
		};
		LocationOptionHtml += self.parseTmplate(tmplate.deliverLocationOption,options);
	}
	
	
	iData.get('locDropDown').empty().append(LocationOptionHtml);
}

dashboard.prototype.parseTmplate = function (tmplHtml, options) {
    var html = tmplHtml;
    for (var key in options) {
        html = html.replace(new RegExp("@{" + key + "}", "gm"), options[key]);
    }
    return html;
}

dashboard.prototype.getCustomerInfoCallback = function(customerData) {
    var self = this,
        keyNames = self.getCustomerInfoKeys();

    if (self.isBrowser) {
        customerData = {"account": "12345678", "fullName": "Nick X L AO", "secureToken": "411768490e203d7171fcd0047754c88454485b74de6863edab12bc043ea3e58", "location": "GLTc"};
    }

    // save customer info to variables
    self.account = customerData[keyNames.account];
    self.location = customerData[keyNames.location];
    self.secureToken = customerData[keyNames.secureToken];
    // get dashboard data from server
    self.viewDashboard();
};

dashboard.prototype.viewDashboard = function() {
    var self = this;

    self.request({
        name: "viewGameDashboard",
        method: "POST",
        data: self.viewDashboardRequestParam,
        callback: self.viewDashboardCallback
    });
};

dashboard.prototype.viewDashboardRequestParam = function() {
    var self = this;

    return {
        account: self.account,
        secureToken: self.secureToken
    };
};

dashboard.prototype.viewDashboardCallback = function() {
    var self = this;

    return {
        "success": function(respData) {
            var data = respData.data,
                body = data.body;

            self.constructDashboard(body);
        },
        "error": function(respData) {
            // DO NOTHING
        }
    };
};

dashboard.prototype.constructDashboard = function(dashboardData) {
    var self = this,
        gameDashboard = dashboardData.gameDashboard,
        dashboardLength = gameDashboard.length,
        gameData, gameDetail, gameLength,
        // location: the game location
        location,
        // game: each of the gameDetail item from server
        // gameDate: the happens date of each gameDetail item
        // gameTime: the happens time within the gameDate
        game, gameDate, gameTime,
        // greenAmount: the amount of the LaiSees happens at the gameTime
        // bonusAmount: the amount of the bigLaiSees happens at the gameTime
        greenAmount, bonusAmount,

        // newGameDashboard: a new object which to store all the game data for the HTML construction
        // newGameData: a new object which to store the game data for each location
        // newGameDetail: a new object which to store all the game details for each location
        // newGame: a new object which to store each game details
        newGameDashboard = {}, newGameData, newGameDetail, newGame,
        // totalGreenAmount: the totalGreenAmount happens within the gameDate
        // totalBonusAmount: the totalBonusAmount happens within the gameDate
        totalGreenAmount, totalBonusAmount,
        // the constructed HTML string
        detailHTML = "";

    // construct the detail object
    for (var i = 0; i < dashboardLength; i++) {
        gameData = gameDashboard[i];
        location = gameData.location;
        gameDetail = gameData.gameDetail;
        gameLength = gameDetail.length;

        // construct object
        newGameDashboard[location] = {};
        newGameData = newGameDashboard[location];

        newGameData.gameAmount = gameData.gameAmount;
        newGameData.greenAmount = gameData.greenAmount;
        newGameData.bonusAmount = gameData.bonusAmount;
        newGameData.remainBudget = gameData.remainBudget;
        newGameData.totalBudget = gameData.totalBudget;
        // new game detail
        newGameData.gameDetail = {};
        newGameDetail = newGameData.gameDetail;

        for (var j = 0; j < gameLength; j++) {
            game = gameDetail[j];
            gameDate = game.date;
            gameTime = game.time;
            greenAmount = +game.greenAmount;
            bonusAmount = +game.bonusAmount;

            newGame = newGameDetail[gameDate];
            // reconstruct a new detail object for HTML construction
            // for example:
            //      var newGameDashboard = {
            //          "location1": {
            //              "gameAmount": gameAmount,
            //              "greenAmount": greenAmount,
            //              "bonusAmount": bonusAmount,
            //              "remainBudget": remainBudget,
            //              "totalBudget": totalBudget,
            //              "gameDetail": {
            //                  "date1": {
            //                      "totalGreenAmount": greenAmount1 + greenAmount2,
            //                      "totalBonusAmount": bonusAmount1 + bonusAmount2,
            //                      "details": [
            //                          {
            //                              "time": "time1",
            //                              "greenAmount": greenAmount1,
            //                              "bonusAmount": bonusAmount1
            //                          },
            //                          {
            //                              "time": "time2",
            //                              "greenAmount": greenAmount2,
            //                              "bonusAmount": bonusAmount2
            //                          }
            //                      ]
            //                  },
            //                  "date2": {
            //                      "totalGreenAmount": greenAmount3,
            //                      "totalBonusAmount": bonusAmount3,
            //                      "details": [
            //                          {
            //                              "time": "time3",
            //                              "greenAmount": greenAmount3,
            //                              "bonusAmount": bonusAmount3
            //                          }
            //                      ]
            //                  }
            //              }
            //          }
            //      };
            if (newGame) {
                newGame.totalGreenAmount += greenAmount;
                newGame.totalBonusAmount += bonusAmount;
                newGame.details.push({
                    time: gameTime,
                    greenAmount: greenAmount,
                    bonusAmount: bonusAmount
                });
            } else {
                newGameDetail[gameDate] = {
                    totalGreenAmount: greenAmount,
                    totalBonusAmount: bonusAmount,
                    details: [{
                        time: gameTime,
                        greenAmount: greenAmount,
                        bonusAmount: bonusAmount
                    }]
                };
            }
        }
    }
    // save newly constructed object to global variable
    self.newGameDashboard = newGameDashboard;

    // update Dashboard details
    self.updateDashboard(self.location);
};

dashboard.prototype.updateDashboard = function(location) {
    var self = this,
        locationData = self.newGameDashboard[location],
        gameDetail,
        dashboradCcy,
        totalGreenAmount, totalBonusAmount,
        detailsLength, detailItem,
        detailHTML = "";

    //iData.get("locSwitcher").text(location).attr("class", location);
    iData.get('locDropDown').val(location);
    if (locationData) {
        // update the total summary, display "0" if no data for the selected location
        self.updateSummary(locationData.gameAmount, locationData.greenAmount, locationData.bonusAmount);
        for(var i = 0; i < self.configuration.settings.GreenPacketLocation.length; i++) {
        	if(self.configuration.settings.GreenPacketLocation[i].value === location) {
        		dashboradCcy = self.configuration.settings.GreenPacketLocation[i].ccy;
        	}
        }
        //Dave
        var amoney=self.formatNumber(locationData.remainBudget, 0);
//        amoney="0";//0余额不足，100之内不足100元，直接注销就是正常
        var amout=dashboradCcy + " " + amoney;




        $('#remainAmount').text(amout);
        $('#remainAmount_nothave').text(amout);
        $('#remainAmount100_nothave').text(amout);

        amoney=amoney.replace(",","");
        var remain_amount=Number(amoney);


        if(remain_amount<=0){
             $('#not_haveAmount_div').show();
        }else{
            if(remain_amount<100){
                $('#not_haveAmount100_div').show();
            }else{
                $('#haveAmount_div').show();
            }
        }
        //Dave end

        // hightlight the budget if the reaminBudget <= totalBudget * 10%;
        if (locationData.remainBudget <= locationData.totalBudget * 0.1) {
            iData.get("remainAmount").css("color", "#ff0");
        } else {
            iData.get("remainAmount").css("color", "#fff");
        }
        //iData.get("remainAmount").text(self._ccyMapping[location] + " " + self.formatNumber(locationData.remainBudget, 0));

        gameDetail = locationData.gameDetail;
        // construct HTML detail list
        $.each(gameDetail, function(date, dateDetail) {
            totalGreenAmount = dateDetail.totalGreenAmount;
            totalBonusAmount = dateDetail.totalBonusAmount;
            detailsLength = dateDetail.details.length;
            detailHTML = detailHTML +
                '<li class="ui-dashboard-item-summary">' +
                    '<span>' + date + '</span>' +
                    //Dave
                    //'<span class="shakes">' + detailsLength + '</span>' +
                    '<span class="laiSees">' + totalGreenAmount + '</span>' +
                    '<span class="bigLaiSees">' + totalBonusAmount + '</span>' +
                    '<ul class="ui-dashboard-item-details">';
            for (var i = 0; i < detailsLength; i++) {
                detailItem = dateDetail.details[i];
                detailHTML = detailHTML +
                        '<li>' +
                            '<span>&nbsp;&nbsp;' + detailItem.time + '</span>' +
                            //Dave
                            //'<span class="shakes">&nbsp;</span>' +
                            '<span class="laiSees">' + detailItem.greenAmount + '</span>' +
                            '<span class="bigLaiSees">' + detailItem.bonusAmount + '</span>' +
                        '</li>';
            }
            detailHTML = detailHTML +
                    '</ul>' +
                '</li>';
        });
    } else {
        // update the total summary, display "0" if no data for the selected location
        iData.get("shakes").text("0");
        iData.get("laiSees").text("0");
        iData.get("bigLaiSees").text("0");
        iData.get("remainAmount").text(dashboradCcy + " 0");
    }

    // update the dashboard details
    iData.get("listDashboard").html(detailHTML);
    // update event listener
    self.updateFastClickEventListener();

    // refresh iScroll plugin
    dashboardIScrollPluginInit.myScroll.refresh();
};

dashboard.prototype.updateSummary = function(gameAmount, greenAmount, bonusAmount) {
    var self = this,
        _i18n = iData.get("i18n"),
        summaryHTML = _i18n.Total,
        shakeHTML = "", laiSeeHTML = "", bigLaiSeeHTML = "";

    shakeHTML = "<span class=\"shakes\">" + gameAmount + "</span> " + (gameAmount < 2 ? _i18n.shake : _i18n.shakes);
    laiSeeHTML = "<span class=\"laiSees\">" + greenAmount + "</span> " + (greenAmount < 2 ? _i18n.LaiSee : _i18n.LaiSees);
    bigLaiSeeHTML = "<span class=\"bigLaiSees\">" + bonusAmount + "</span> " + (bonusAmount < 2 ? _i18n.bigLaiSee : _i18n.bigLaiSees);

    summaryHTML = summaryHTML + "  " + laiSeeHTML + " " + bigLaiSeeHTML;
    iData.get("summary").html(summaryHTML);
};

dashboard.prototype.updateFastClickEventListener = function() {
    var self = this,
        $li = iData.get("listDashboard").find(".ui-dashboard-item-summary");

    $li.each(function(i){
		$(this).fastClick(function() {
			if ($(this).hasClass("expanded")) {
				$(this).removeClass("expanded");
			} else {
				$(this).addClass("expanded");
			}
		});
	});
};

dashboard.prototype.initLocSwither = function() {
    var self = this;
       /*var startPos, endPos, origPos, point,
        $locSwitcher = iData.get("locSwitcher"),
        distance = $locSwitcher.closest("div").width() - $locSwitcher.width(),
        threshold = distance / 2,
        supportTouch = "ontouchstart" in window,
        START_EV = "mousedown", MOVE_EV = "mousemove", END_EV = "mouseup mouseleave",
        isStart = false, isMoving = false,
        resetPosition = function() {
            $locSwitcher.stop().animate({
                "left": origPos
            }, 200, function() {
                isMoving = false;
            });
        },
        setPosition = function(isClick) {
            if (isClick || +$locSwitcher.css("left").split("px")[0] != origPos) {
                if ($locSwitcher.hasClass(self._location1)) {
                    $locSwitcher.stop().animate({
                        "left": distance
                    }, 200, function() {
                        isMoving = false;
                        $(this).text(iData.get("i18n").location2).attr("class", self._location2);
                        self.updateDashboard(self._location2);
                    });
                } else {
                    $locSwitcher.stop().animate({
                        "left": 0
                    }, 200, function() {
                        isMoving = false;
                        $(this).text(iData.get("i18n").location1).attr("class", self._location1);
                        self.updateDashboard(self._location1);
                    });
                }
            }
        };
        
    // check if support touch event
    if (supportTouch) {
        START_EV = "touchstart";
        MOVE_EV = "touchmove";
        END_EV = "touchend touchcancel";
    }

    $locSwitcher.on(START_EV, function(e) {
        isStart = true;
        origPos = +$locSwitcher.css("left").split("px")[0];
        point = e.originalEvent.touches ? e.originalEvent.touches[0] : e;
        startPos = point.pageX;
        // move the switch button when mouse or touch moving
    }).on(MOVE_EV, function(e) {
        e.preventDefault();
        if (isStart) {
            isMoving = true;
            point = e.originalEvent.touches ? e.originalEvent.touches[0] : e;
            endPos = point.pageX;
            targetPos = origPos + (endPos - startPos);
            if (targetPos > distance) {
                targetPos = distance;
            } else if (targetPos < 0) {
                targetPos = 0;
            }
            $locSwitcher.css({
                "left": targetPos
            });
        }
    }).on(END_EV, function(e) {
        if (isStart) {
            isStart = false;
            if (endPos - startPos > threshold || endPos - startPos < -threshold) {
                setPosition();
            } else {
                resetPosition();
            }
        }
        // event fired when mouse move out of the target element
        // or too many touch points
    }).closest("div").click(function(e) {
        e.preventDefault();
        // prevent click event trigger together with end event
        if (!isMoving) {
            setPosition(true);
        }
    });
    */
    iData.get('locDropDown').on('change',function(){
    	self.updateDashboard($(this).val());
    });
};

dashboard.prototype.formatNumber = function (number, decimal, decimal_point, thousands_separator) {
    number = (number + '').replace(/[^0-9+-Ee.]/g, '');
    number = number.replace(/,/g, '');
    decimal = !isFinite(+decimal) ? 2 : Math.abs(decimal);
    decimal_point = (typeof decimal_point === 'undefined') ? '.' : decimal_point;
    thousands_separator = (typeof thousands_separator === 'undefined') ? ',' : thousands_separator;
    var num = !isFinite(+number) ? 0 : parseFloat(+number).toFixed(decimal),
        str = num.split(decimal_point);
    if (str[0].length > 3) {
        str[0] = str[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, thousands_separator);
    }
    return str.join(decimal_point);
};

// iScroll plugin for the record list
var dashboardIScrollPluginInit = {
    myScroll: null,
    begin: function() {
        dashboardIScrollPluginInit.myScroll = new iScroll("wrapper", {
            checkDOMChanges: true,
            hScrollbar: false,
            vScrollbar: false
        });
    }
};

dashboard.prototype.buildModel = function() {
    var self = this,
        GLOBAL_CONFIG = self.configuration.settings;

    // for browser mode
    self.isBrowser = GLOBAL_CONFIG.isBrowser;

    iData.add({
        // nav buttons
        "btnHome": $("#btnHome"),
        "btnDelivered": $("#btnDelivered"),
        "btnDashboard": $("#btnDashboard"),
        "btnReceived": $("#btnReceived"),
        //"locSwitcher": $("#locSwitcher"),
        "locDropDown": $("#locDropDown"),
        // total summary
        "summary": $("#summary"),
        "shakes": $("#shakes"),
        "laiSees": $("#laiSees"),
        "bigLaiSees": $("#bigLaiSees"),
        "remainAmount": $("#remainAmount"),
        // details
        "listDashboard": $("#listDashboard")
    });
};

dashboard.superclass = iFunction;
dashboard.start = function() {
    return new dashboard();
};
iClass(dashboard);